//
//  PlayerViewController.m
//  LiTingFeng
//
//  Created by xinxuan on 16/3/2.
//  Copyright © 2016年 Bullgo. All rights reserved.
//

#import "PlayerViewController.h"
//#import "wifiFtpServerStartViewController.h"
#import "rootViewController.h"
#import "MusicsData.h"
#import "Colours.h"
#import <MediaPlayer/MediaPlayer.h>
#import "PrivateValues.h"
#import "Macro.h"
#define YDIMG(__name) [UIImage imageNamed:__name]
@interface PlayerViewController ()
{
    NSMutableArray *arrMutableDeleteSource; //存储需要删除的条目
    
}
@property (strong) CAEmitterLayer *heartsEmitter;
@property (nonatomic,strong) UITableView *selectTabV;//抽屉tableView


-(void)lastSong;    //下一曲
-(void)nextSong;    //上一曲
-(void)refreshMusicList;    //更新音乐列表

-(void)playTheSongAtIndex:(int)index;   //播放选中歌曲

-(BOOL)isMusicExist;//检查乐库是否有歌，没有的话就不播放

@end

@implementation PlayerViewController
static NSString * identifier = @"reuse";
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}

-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:NOTIFICATION_UPDATE_MUSCI_CURRENT_INDEX object:nil];
    
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //接受后台控制。。播放音乐切换
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    //[MusicsData copyFileDatabase];
    
    [self layOut];
    [self addNavigitionButton];
    // 增加分类标题的界面
    [self selectTabV];
    
    [self addHeaderView];
    
    [self setUpCircularProgressView];   //设置进度条
    
    //若有歌曲就进行播放，若没有歌曲就到wifi页面让他自行添加
    if ([MusicsData loadAllMusics].count) {
        [self startPlayer];
    }
    else{
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Music Not Found"  message:@"Please connect to this iPhone through network, and upload your favorite musics to your 立挺峰." preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"Get it" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            rootViewController * rootVC = [[rootViewController alloc]init];
            [self.navigationController pushViewController:rootVC animated:YES];
            
        }];
        
        [alertController addAction:otherAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playTheSong:) name:NOTIFICATION_UPDATE_MUSCI_CURRENT_INDEX object:nil];
    
}


////更新界面数据
#pragma mark-
-(void)updateMusicInfo
{
    NSDictionary *dicTemp = [MusicsData loadCurrentMusicInfo];
    self.labArtist.text = [dicTemp objectForKey:MUSIC_CURRENT_ARTIST];
    self.labSongName.text = [dicTemp objectForKey:MUSIC_CURRENT_TITLE];
}

-(void)addHeaderView
{
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, Screen_Width,44 )];
    label.text = [NSString stringWithFormat:@"   播放队列"];
    label.font = [UIFont boldSystemFontOfSize:17];
    _selectTabV.tableHeaderView = label;
    
    UIButton * addBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    addBtn.frame = CGRectMake(0, 0, Screen_Width, 44);
    [addBtn addTarget:self action:@selector(add:) forControlEvents:(UIControlEventTouchUpInside)];
    [addBtn setTitle:@"添加 + " forState:(UIControlStateNormal)];
    addBtn.tintColor = [UIColor wheatColor];
    addBtn.backgroundColor = [UIColor blackColor];
    
    _selectTabV.tableFooterView = addBtn;
    
}




-(void)add:(UIButton*)sender{
    
    rootViewController * rootVC = [[rootViewController alloc]init];
    [self.navigationController pushViewController:rootVC animated:YES];
    
}


-(void)viewWillAppear:(BOOL)animated
{

    [self.navigationController.navigationBar setBarTintColor:[UIColor colorFromHexString:@"#000000"]];
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
    NSString *strIsPlaying = [PrivateValues getValueForKey:PLIST_IS_MUSIC_PLAYING];
    if ([strIsPlaying isEqualToString:@"YES"]) {
        self.btnPlay.selected = YES;
    }else{
        self.btnPlay.selected = NO;
    }
    
    if (!self.btnPlay.on) {

    }
    //接受后台控制
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
    [self recordForIOS7];
    
}




-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBarTintColor:navigatinBar_color_default];
    self.tabBarController.tabBar.hidden = NO;
    [self.music_slider stop];
    //停止后台控制
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
    //[eq stop];
}


- (void)layOut{
    
    if (Screen_Width == 320 && Screen_Height == 480) {//苹果4
        
        self.place1.constant =  20;
        self.imageWidth.constant = 150;
        self.imageUpWidth.constant = 20;
        self.timeUpSpace.constant =  27;
        self.lastUpSpace.constant = self.nextUpSpace.constant = 13;
        self.playModeUpSpace.constant = 33;
        self.playUpSpace.constant = 6;
        
    }else if(Screen_Width == 320 && Screen_Height == 568){//苹果5
        
        self.place1.constant =  20;
        self.imageWidth.constant = 150;
        self.imageUpWidth.constant = 20;
        self.timeUpSpace.constant =  27;
        self.lastUpSpace.constant = self.nextUpSpace.constant = 13;
        self.playModeUpSpace.constant = 33;
        self.playUpSpace.constant = 6;
        
        
    }else if(Screen_Width == 375 && Screen_Height == 667){//苹果6
        self.place1.constant =  30;
        self.imageWidth.constant = 230;
        self.timeUpSpace.constant =  37;
        self.lastSpace.constant = self.nextSpace.constant = 46;
    }else{//苹果6puls及其以上
        
        self.place1.constant =  30;
        self.imageWidth.constant = 230;
        self.timeUpSpace.constant =  37;
        self.lastSpace.constant = self.nextSpace.constant = 46;
        
    }
}




-(void)recordForIOS7{
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        //AVAudioSessionCategoryPlayAndRecord用于录音和播放
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if(session == nil)
            NSLog(@"Error creating session: %@", [sessionError description]);
        else
            [session setActive:YES error:nil];
    }
}



#pragma mark -
-(BOOL)shouldAutorotate{
    return NO;
}

#pragma mark -
-(BOOL)canBecomeFirstResponder{
    return  YES;
}


#pragma mark -
-(BOOL)isMusicExist
{
    if ([MusicsData sharedInstance].arrMusic.count) {
        return YES;
    }else
        return NO;
}
#pragma mark - PCSEQ



//初始化CircularProgressView
- (void)setUpCircularProgressView{
    self.music_slider.value = 0.0f;
    
    [self.music_slider setThumbImage:YDIMG(@"player-progress-point") forState:UIControlStateNormal];
    [self.music_slider setThumbImage:YDIMG(@"player-progress-point-h") forState:UIControlStateHighlighted];
    [self.music_slider setMinimumTrackImage:[YDIMG(@"player-progress-h") resizableImageWithCapInsets:UIEdgeInsetsMake(4, 3, 5, 4) resizingMode:UIImageResizingModeStretch]];
    [self.music_slider setMiddleTrackImage:[YDIMG(@"player-progress-h") resizableImageWithCapInsets:UIEdgeInsetsMake(4, 3, 5, 4) resizingMode:UIImageResizingModeStretch]];
    [self.music_slider setMaximumTrackImage:[YDIMG(@"player-progress-h") resizableImageWithCapInsets:UIEdgeInsetsMake(4, 3, 5, 4) resizingMode:UIImageResizingModeStretch]];
    
    self.music_slider.delegate = self;
    
    
    self.btnPlay.on = YES;
    self.playmode = playModeCirculate;//初始化播放模式
}

//播放当前歌曲
- (void)startPlayer{
    
    self.music_slider.audioPath = [MusicsData getProgressAudioPath];
    [self.music_slider play];
    
    self.music_slider.playOrPauseButtonIsPlaying = YES;
    self.music_slider.player.volume = 1.0f;
    self.btnPlay.on = NO;
    [PrivateValues saveValue:@"YES" forKey:PLIST_IS_MUSIC_PLAYING];
    [self btnPlayStateChange];
    
    NSUInteger nextIndex = [MusicsData getIndexCutrentMusic];
    NSData *imgData = [[MusicsData sharedInstance].arrMusicArtwork objectAtIndex:nextIndex];
    [self.cover_Img setImage:[UIImage imageWithData:imgData]];
    
    //填充页面数据
    NSDictionary *dicTemp = [MusicsData loadCurrentMusicInfo];
    self.labArtist.text = [dicTemp objectForKey:MUSIC_CURRENT_ARTIST];
    self.labSongName.text = [dicTemp objectForKey:MUSIC_CURRENT_TITLE];
    
}

//修改播放按钮状态
- (void)btnPlayStateChange{
    if (self.btnPlay.on) {
        self.btnPlay.selected = NO;
    }else{
        self.btnPlay.selected = YES;
    }
}

#pragma mark - Circle
#pragma mark Circular Progress View Delegate method
- (void)btnStateChange:(BOOL)isOn{
    self.btnPlay.on = isOn;
    [self btnPlayStateChange];
}

- (void)updateProgressViewWithPlayer:(AVAudioPlayer *)player {
    //update timeLabel
    int restTime =(int)player.currentTime;
    self.labRestTime.text = [NSString stringWithFormat:@"%@",[self formatTime:restTime]];
    int sumTime =(int)player.duration;
    self.labSumTime.text = [NSString stringWithFormat:@"%@",[self formatTime:(int)sumTime]];
}

- (void)updatePlayOrPauseButton{
    self.btnPlay.on = YES;
}

//歌曲结束播放时(自然结束)
- (void)playerDidFinishPlaying{
    switch (self.playmode) {
            //单曲播放
        case playModeSingle:{
            self.labRestTime.text = [NSString stringWithFormat:@"%@",[self formatTime:(int)self.music_slider.duration]];
            [self startPlayer];
        }
            break;
            
        case playModeRandom:{
            //乱序播放
            [MusicsData setIndexCutrentMusic:rand()%([MusicsData sharedInstance].arrMusic.count)];
            [self startPlayer];
        }break;
            
        case playModeCirculate:{
            //顺序循环
            if ([MusicsData getIndexCutrentMusic] == [MusicsData sharedInstance].arrMusic.count-1)
            {
                //停止当前播放，并跳到第一首歌去
                [MusicsData setIndexCutrentMusic: 0];
                [self startPlayer];
            }
            else
            {
                //跳到下一首歌去播放
                int iTemp =[MusicsData getIndexCutrentMusic];
                iTemp += 1;
                [MusicsData setIndexCutrentMusic:iTemp];
                [self startPlayer];
            }
            
        }break;
            
        default:
            break;
    }
    
}

#pragma mark format audio time
- (NSString *)formatTime:(int)num{
    int sec = num % 60;
    int min = num / 60;
    if (num < 60) {
        return [NSString stringWithFormat:@"00:%02d",num];
    }
    return [NSString stringWithFormat:@"%02d:%02d",min,sec];
}


//播放
- (IBAction)actPlay:(id)sender {
    
    if ([self isMusicExist]) {
        if (self.btnPlay.on) {
            [self.music_slider pause];
            self.music_slider.playOrPauseButtonIsPlaying = YES;
            [sender setBackgroundImage:[UIImage imageNamed:@"暂停"] forState:UIControlStateNormal];
            //[eq stop];
            [PrivateValues saveValue:@"NO" forKey:PLIST_IS_MUSIC_PLAYING];
        }else {
            [self.music_slider play];
            //[eq start];
            self.music_slider.playOrPauseButtonIsPlaying = NO;
            [PrivateValues saveValue:@"YES" forKey:PLIST_IS_MUSIC_PLAYING];
            [sender setBackgroundImage:[UIImage imageNamed:@"播放"] forState:UIControlStateNormal];
        }
        [self btnPlayStateChange];
    }
    
}
//上一首
- (IBAction)actPaUp:(id)sender {
    if ([self isMusicExist]) {
        // [eq stop];
        [self lastSong];
        //[eq start];
    }
}
//下一首
- (IBAction)actPaDown:(id)sender {
    if ([self isMusicExist]) {
        // [eq stop];
        [self nextSong];
        // [eq start];
    }
}

//歌单
- (IBAction)btnMusicList:(id)sender {
    
    UIButton * btn = (UIButton*)sender;
    
    if (btn.selected) {
        [self packUp];
    }else{
        [self packUp];
        
    }
    
    
}


#pragma mark - 展出或收起展示所有项目的界面
- (void)packUp
{
    
    
    if ([_selectTabV isHidden] == YES)
    {
        [_selectTabV setHidden:NO];
        [UIView animateWithDuration:0.6 animations:^
         {
             [_selectTabV setFrame:CGRectMake(0, 100, self.view.frame.size.width, 400)];
         } completion:^(BOOL finished)
         {
         }];
    }else
    {
        [UIView animateWithDuration:0.6 animations:^
         {
             [_selectTabV setFrame:CGRectMake(self.view.frame.size.width, 100, self.view.frame.size.width, 400)];
         } completion:^(BOOL finished)
         {
             [_selectTabV setHidden:YES];
         }];
    }
    
}

//刷新歌曲
- (IBAction)actRefreshData:(id)sender {
    [self refreshMusicList];
}

//循环模式
- (IBAction)actChangePlayMode:(UIButton *)sender {
    switch (self.playmode) {
            
        case playModeSingle:{
            self.playmode = playModeRandom;
            [sender setBackgroundImage:[UIImage imageNamed:@"随机播放"] forState:UIControlStateNormal];
        }break;
        case playModeRandom:{
            self.playmode = playModeCirculate;
            [sender setBackgroundImage:[UIImage imageNamed:@"顺序循环"] forState:UIControlStateNormal];
        }
            break;
        case playModeCirculate:{
            self.playmode = playModeSingle;
            [sender setBackgroundImage:[UIImage imageNamed:@"单曲循环"] forState:UIControlStateNormal];
        }
        default:
            break;
    }
    
}


#pragma mark - Notifications
-(void)lastSong
{
    if ([self isMusicExist]) {
        
        switch (self.playmode) {
                //单曲播放
            case playModeSingle:{
                self.labRestTime.text = [NSString stringWithFormat:@"%@",[self formatTime:(int)self.music_slider.duration]];
                [self startPlayer];
            }
                break;
                
            case playModeRandom:{
                //乱序播放
                int randIndex = rand()%[MusicsData sharedInstance].arrMusic.count;
                [MusicsData setIndexCutrentMusic:randIndex];
                [self startPlayer];
            }break;
                
            case playModeCirculate:{
                //顺序循环
                if ([MusicsData getIndexCutrentMusic]==0)
                {
                    [MusicsData setIndexCutrentMusic:(int)([MusicsData sharedInstance].arrMusic.count - 1)];
                    [self startPlayer];
                }
                else
                {
                    int iTemp =[MusicsData getIndexCutrentMusic];
                    iTemp -= 1;
                    [MusicsData setIndexCutrentMusic:iTemp];
                    [self startPlayer];
                }
                
                
            }break;
                
            default:
                break;
        }
        
    }
    
}
-(void)nextSong
{
    if ([self isMusicExist]) {
        switch (self.playmode) {
                //单曲播放
            case playModeSingle:{
                self.labRestTime.text = [NSString stringWithFormat:@"%@",[self formatTime:(int)self.music_slider.duration]];
                [self startPlayer];
            }
                break;
                
            case playModeRandom:{
                //乱序播放
                int randIndex = rand()%[MusicsData sharedInstance].arrMusic.count;
                [MusicsData setIndexCutrentMusic:randIndex];
                [self startPlayer];
            }break;
                
            case playModeCirculate:{
                //顺序循环
                if ([MusicsData getIndexCutrentMusic] == [MusicsData sharedInstance].arrMusic.count-1)
                {
                    //停止当前播放，并跳到第一首歌去
                    [MusicsData setIndexCutrentMusic: 0];
                    [self startPlayer];
                }
                else
                {
                    //跳到下一首歌去播放
                    int iTemp =[MusicsData getIndexCutrentMusic];
                    iTemp += 1;
                    [MusicsData setIndexCutrentMusic:iTemp];
                    [self startPlayer];
                }
                
            }break;
                
            default:
                break;
        }
        
    }
    
}

-(void)refreshMusicList
{
    [MusicsData loadAllMusics];
    [self.selectTabV reloadData];
}

-(void)playTheSong:(NSNotification*)sender
{
    NSNumber *num = [sender object];
    int index = num.intValue;
    
    [self playTheSongAtIndex:index];
}
-(void)playOrPauseTheSong
{
    self.btnPlay.on = !self.btnPlay.on;
    if (self.btnPlay.on) {
        [self.music_slider pause];
        self.music_slider.playOrPauseButtonIsPlaying = YES;
    }else {
        [self.music_slider play];
        self.music_slider.playOrPauseButtonIsPlaying = NO;
    }
}
#pragma mark - Collection Relativity

-(void)playTheSongAtIndex:(int)index{
    [MusicsData setIndexCutrentMusic:index];
    [self startPlayer];
}

#pragma tableView的懒加载
-(UITableView *)selectTabV{
    if (_selectTabV == nil) {
        _selectTabV =[[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 100, self.view.frame.size.width, 400)];
        _selectTabV.backgroundColor = [UIColor  whiteColor];
        [_selectTabV setHidden:YES];
        _selectTabV.delegate = self;
        _selectTabV.dataSource = self;
        _selectTabV.backgroundColor = [UIColor whiteColor];
        //分割线
        [self.selectTabV   setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
        [self.selectTabV   setSeparatorColor:[UIColor black25PercentColor]];
        [self updateMusicInfo];
        [_selectTabV registerClass:[UITableViewCell class] forCellReuseIdentifier:identifier];
        [self.view insertSubview:_selectTabV aboveSubview:self.music_slider];
    }
    return _selectTabV;
    
    
}
#pragma mark tableView 的代理方法

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [MusicsData sharedInstance].arrMusic.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 60;
    
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    
    cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.textLabel.text = [[MusicsData sharedInstance].arrMusic objectAtIndex:indexPath.item];
//    NSString *strArtist = [[MusicsData sharedInstance].arrMusicArtist objectAtIndex:indexPath.item];
//    
//    cell.detailTextLabel.text = strArtist;
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!tableView.editing) {
        // 加上此句，返回时直接就是非选中状态。
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATION_UPDATE_MUSCI_CURRENT_INDEX object:[NSNumber numberWithLong:indexPath.item]];
        [self updateMusicInfo];
    }
    
    
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [arrMutableDeleteSource removeObject:indexPath];
}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return NO;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}




/*
 自定义UInavigationBar的按钮
 */
-(void)addNavigitionButton{
    NSMutableArray * rightBtns = [NSMutableArray array];
    for (int i =0; i< 7 ; i++) {
        UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
        if (Screen_Width == 320 && Screen_Height == 480) {//苹果4
            btn.frame = CGRectMake(0, 0, 30, 30);
            
        }else if(Screen_Width == 320 && Screen_Height == 568){//苹果5
            
            btn.frame = CGRectMake(0, 0, 30, 30);
            
        }else{
            btn.frame = CGRectMake(0, 0, 38, 38);
        }
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png",i+1]] forState:UIControlStateNormal];
        
        [btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d点击.png",i+1]] forState:UIControlStateHighlighted];
        btn.tag = 1000 + i;
        [btn addTarget:self action:@selector(levelTouch:) forControlEvents:(UIControlEventTouchUpInside)];
        UIBarButtonItem *barSearchBtn=[[UIBarButtonItem alloc]initWithCustomView:btn];
        [rightBtns addObject:barSearchBtn];
        
    }
    
    self.navigationItem.rightBarButtonItems=rightBtns;
    
}

-(void)levelTouch:(UIButton*)sender{
    
    switch (sender.tag) {
        case 1000:
            //做一些对应等级的操作
            NSLog(@"1");
            break;
        case 1001:
            NSLog(@"2");
            break;
        case 1002:
            NSLog(@"3");
            break;
        case 1003:
            NSLog(@"4");
            break;
        case 1004:
            NSLog(@"5");
            break;
        case 1005:
            NSLog(@"6");
            break;
        case 1006:
            NSLog(@"7");
            break;
        default:
            break;
            
    }
    
}


@end
